package com.eliza.module.view.work


import android.app.Activity
import android.content.ComponentName
import android.content.Intent
import android.os.Bundle
import android.provider.MediaStore
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Column
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.work.Constraints
import androidx.work.Constraints.ContentUriTrigger
import androidx.work.Data
import androidx.work.NetworkType
import androidx.work.OneTimeWorkRequest
import androidx.work.WorkInfo
import androidx.work.WorkManager
import androidx.work.multiprocess.RemoteListenableWorker.ARGUMENT_CLASS_NAME
import androidx.work.multiprocess.RemoteListenableWorker.ARGUMENT_PACKAGE_NAME
import androidx.work.workDataOf
import com.eliza.module.InfiniteWorker
import com.eliza.module.TestFileWorker
import com.eliza.module.TestWorker
import com.eliza.module.view.work.imageprocessing.WorkImageProcessingActivity
import com.eliza.module.view.work.sherlockholmes.AnalyzeSherlockHolmesActivity
import kotlin.random.Random


/*
*
*
* 使用 WorkManager API 可以轻松地调度那些必须可靠运行的可延期异步任务。
* 通过这些 API，您可以创建任务并提交给 WorkManager，以便在满足工作约束条件时运行。
* */
class WorkMainActivity : ComponentActivity() {
    private val workManager: WorkManager by lazy { WorkManager.getInstance(this) }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            WorkBasic.Show(workManager = workManager)
        }
    }

    private fun oneTimeWorkRemoteWorkRequest(componentName: ComponentName): OneTimeWorkRequest {
        val data = workDataOf(
            ARGUMENT_PACKAGE_NAME to componentName.packageName,
            ARGUMENT_CLASS_NAME to componentName.className,
        )
        return OneTimeWorkRequest.Builder(RemoteWorker::class.java).setInputData(data)
            .setConstraints(Constraints(requiredNetworkType = NetworkType.CONNECTED)).build()
    }
}


object WorkBasic {
    var btnx: @Composable (text: String, onClick: () -> Unit) -> Unit = { t, c ->
        Button(onClick = c) {
            Text(text = t)
        }
    }

    @Composable
    fun Show(workManager: WorkManager) {
        basic(workManager = workManager)
        conditionX(workManager = workManager)
    }

    @Composable
    fun basic(workManager: WorkManager) {
        val context = LocalContext.current
        val lifecycleOwner = LocalLifecycleOwner.current
        val activity = context as Activity
        Column {
            //===============
            btnx("cancelAllWork") {
                workManager.cancelAllWork()
            }
            var infoText by remember {
                mutableStateOf("")
            }
            var statusText by remember {
                mutableStateOf("")
            }
            btnx("OneTimeWorkRequest:Run LogE Infinite Work") {
                val request = OneTimeWorkRequest.Builder(InfiniteWorker::class.java)
                    .setConstraints(Constraints(requiresCharging = true)).build()
                val enqueue = workManager.enqueue(
                    request
                )
                val status = workManager.getWorkInfoByIdLiveData(request.id)
                status.observe(lifecycleOwner, fun(info: WorkInfo) {
                    statusText = "${info.id} ${info.tags} ${info.state.isFinished}"
                })
                infoText =
                    "value${enqueue.state.value} isDone${enqueue.result.isDone} isCancelled${enqueue.result.isCancelled}"
                workManager.cancelWorkById(request.id)
            }
            Text(text = infoText)
            Text(text = statusText)
            btnx("Chain Work") {
                val request1 = OneTimeWorkRequest.Builder(InfiniteWorker::class.java).build()
                val request2 = OneTimeWorkRequest.Builder(TestWorker::class.java).build()
                val request3 = OneTimeWorkRequest.Builder(TestWorker::class.java).build()
//                workManager.beginWith(request1).then(request3).then(request2)
                workManager.enqueue(listOf(request1, request3, request2))
            }

            btnx("Params") {
                val build = OneTimeWorkRequest.Builder(TestFileWorker::class.java).setInputData(
                    Data.Builder().apply {
                        putInt("KEY", Random.nextInt(1))
                    }.build()
                ).setConstraints(Constraints(requiresBatteryNotLow = true)).build()
                workManager.enqueue(
                    build
                )
            }

            btnx("Sherlock Holmes") {
                context.startActivity(
                    Intent(activity, AnalyzeSherlockHolmesActivity::class.java)
                )
            }
            btnx("Image Processing") {
                context.startActivity(
                    Intent(activity, WorkImageProcessingActivity::class.java)
                )
            }
            btnx("Observe Image URI") {
                val constraints = Constraints(
                    contentUriTriggers = setOf(
                        ContentUriTrigger(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, true)
                    )
                )
                workManager.enqueue(
                    ToastWorker.create("Image URI Updated!").setConstraints(constraints).build()
                )

            }
        }
    }

    @Composable
    fun conditionX(workManager: WorkManager) {
        Column {
            btnx("Condition:Network CONNECTED") {
                //WorkRequest 可以接受Constraints、输入（请参阅Data）和退避条件
                workManager.enqueue(
                    OneTimeWorkRequest.Builder(InfiniteWorker::class.java)
                        .setConstraints(Constraints(requiredNetworkType = NetworkType.CONNECTED))
                        .build()
                )
            }
            btnx("Condition:requiresBatteryNotLow") {
                workManager.enqueue(
                    OneTimeWorkRequest.Builder(TestWorker::class.java)
                        .setConstraints(Constraints(requiresBatteryNotLow = true)).build()
                )
            }
        }
    }
}

